//
//  BindViewController.swift
//  miaoyin
//
//  Created by David on 2017/3/30.
//  Copyright © 2017年 David. All rights reserved.
//

import UIKit

enum BindAccountType{
    case weixin
    case qq
}

class BindViewController: UIViewController {

    override var preferredStatusBarStyle: UIStatusBarStyle{
        return .lightContent
    }
    
    var navigationBar: UINavigationBar!
    
    var phoneInput: FCLoginInput!
    var verifyInput: FCLoginInput!
    
    var getSmsCodeBtn: UIButton!
    
    var submitBtn: UIButton!
    
    var bindType: BindAccountType = .weixin
    
    var step2 = false
    
    var smsCountdown = 60
    
    var code:String?
    var openid: String?
    
    var loadingView: LLFullScreenLoading!
    
    convenience init(bindType: BindAccountType, code: String?, openid: String?){
        self.init()
        self.bindType = bindType
        self.code = code
        self.openid = openid
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        view.backgroundColor = UIColor.white
        
        navigationBar = UINavigationBar(frame: CGRect(x: 0, y: 0, width: self.view.frame.width, height: 64))
        view.addSubview(navigationBar)
        navigationBar.barStyle = .black
        navigationBar.barTintColor = Fatcat.THEME_COLOR
        navigationBar.tintColor = UIColor.white
        
        let navItem = UINavigationItem(title: "绑定手机号")
        navigationBar.pushItem(navItem, animated: true)
        
        navItem.leftBarButtonItem = UIBarButtonItem(barButtonSystemItem: .stop, target: self, action: #selector(UDRegViewController.dismissAll))
        
        view.addSubview(navigationBar)
        
        phoneInput = FCLoginInput(frame: CGRect(x: 16, y: 100, width: view.frame.width - 32, height: 44), type: .phone)
//        phoneInput.maxLength = 11
        phoneInput.input.returnKeyType = .done
        phoneInput.input.addTarget(self, action: #selector(BindViewController.inputBlur(input:)), for: .editingDidEndOnExit)
        view.addSubview(phoneInput)
        
        verifyInput = FCLoginInput(frame: CGRect(x: 16, y: 160, width: view.frame.width - 128, height: 44), type: .verify)
        verifyInput.input.returnKeyType = .done
        verifyInput.input.addTarget(self, action: #selector(BindViewController.inputBlur(input:)), for: .editingDidEndOnExit)
        verifyInput.alpha = 0
        view.addSubview(verifyInput)
        
        getSmsCodeBtn = UIButton(frame: CGRect(x: self.view.frame.width - 108, y: 160 + 8, width: 96, height: 28))
        getSmsCodeBtn.setTitle("获取验证码", for: UIControlState())
        getSmsCodeBtn.setTitleColor(themeColor2, for: UIControlState())
        getSmsCodeBtn.titleLabel?.font = UIFont.systemFont(ofSize: 14)
        getSmsCodeBtn.layer.cornerRadius = 4
        getSmsCodeBtn.layer.borderColor = themeColor2.cgColor
        getSmsCodeBtn.layer.borderWidth = 1
        getSmsCodeBtn.alpha = 0
        view.addSubview(getSmsCodeBtn)
        getSmsCodeBtn.addTarget(self, action: #selector(BindViewController.getSmsCode), for: .touchUpInside)
        
        submitBtn = UIButton(frame: CGRect(x: 16, y: 160, width: view.frame.width - 32, height: 44))
        submitBtn.setTitle("下一步", for: .normal)
        submitBtn.setTitleColor(UIColor.white, for: .normal)
        submitBtn.backgroundColor = themeColor1
        submitBtn.layer.cornerRadius = 4
        view.addSubview(submitBtn)
        submitBtn.addTarget(self, action: #selector(BindViewController.nextStep), for: .touchUpInside)
        
        loadingView = LLFullScreenLoading(frame: view.frame)
        loadingView.alpha = 0
        view.addSubview(loadingView)
        
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(UDRegViewController.resendSmsTimer), userInfo: nil, repeats: true)
    }

    func inputBlur(input: UITextField){
        input.resignFirstResponder()
    }
    
    func nextStep(){
        if phoneInput.input.text == ""{
            phoneInput.input.becomeFirstResponder()
            return
        }
        
        if step2 {
            if verifyInput.input.text == "" {
                verifyInput.input.becomeFirstResponder()
                return
            }
            
            var req = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=user&a=userBinding")!)
            req.httpMethod = "POST"
            
            let postData = "type=\(bindType == .weixin ? "wechat" : "qq")&code=\(verifyInput.input.text!)&openid=\(openid ?? "")"
            print(postData)
            req.httpBody = postData.data(using: .utf8)
            
            loadingView.alpha = 1
            
            URLSession.shared.dataTask(with: req, completionHandler: { (data, _, err) in
                do{
                    DispatchQueue.main.async {
                        self.loadingView.alpha = 0
                    }
                    
                    if err != nil{
                        throw err!
                    }
                    
                    print(String(data: data!, encoding: .utf8) ?? "data nil")
                    
                    let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                    let reCode = jsonObj?.object(forKey: "code") as? Int
                    if reCode == 200 {
                        DispatchQueue.main.async {
                            
                            let cookies = HTTPCookieStorage.shared.cookies!
                            let cookiesData = NSKeyedArchiver.archivedData(withRootObject: cookies)
                            UserDefaults.standard.set(cookiesData, forKey: cookieKey)
                            UserDefaults.standard.set(self.phoneInput.input.text!, forKey: loginUserDefaultKeyName)
                            
                            self.dismissAll()
                        }
                    }else{
                        let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                        alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                        DispatchQueue.main.async {
                            self.present(alert, animated: true, completion: nil)
                        }
                    }
                    
                }catch let ex{
                    let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }
                    print(ex)
                }
            }).resume()
            
            return
        }
        
        getSmsCode()
    }
    
    func getSmsCode(){
        
        if phoneInput.input.text == ""{
            phoneInput.input.becomeFirstResponder()
            return
        }
        
        var req = URLRequest(url: URL(string: "\(apiBaseDomainName)?m=admin&c=user&a=smsBinding")!)
        req.httpMethod = "POST"
        let postData = "type=\(bindType == .weixin ? "wechat" : "qq")&username=\(phoneInput.input.text!)"
        print(postData)
        req.httpBody = postData.data(using: .utf8)
        loadingView.alpha = 1
        URLSession.shared.dataTask(with: req) { (data, _, err) in
            do{
                DispatchQueue.main.async {
                    self.loadingView.alpha = 0
                }
                if err != nil{
                    throw err!
                }
                
                print(String(data: data!, encoding: .utf8) ?? "data nil")
                
                let jsonObj = try JSONSerialization.jsonObject(with: data!, options: .allowFragments) as? NSDictionary
                let reCode = jsonObj?.object(forKey: "code") as? Int
                if reCode == 200 {
                    
                    DispatchQueue.main.async {
                        self.phoneInput.input.isEnabled = false
                        self.verifyInput.alpha = 1
                        self.getSmsCodeBtn.alpha = 1
                        self.getSmsCodeBtn.setTitle("60s", for: .normal)
                        self.getSmsCodeBtn.isEnabled = false
                        
                        if !self.step2 {
                            self.submitBtn.frame = CGRect(origin: CGPoint(x: self.submitBtn.frame.origin.x, y: self.submitBtn.frame.origin.y + 60), size: self.submitBtn.frame.size)
                        }
                        
                        self.verifyInput.becomeFirstResponder()
                        self.step2 = true
                    }
                }else if reCode == 202 {
                    let regVC = UDRegViewController(bindUsername: self.phoneInput.input.text)
                    DispatchQueue.main.async {
                        self.navigationController?.pushViewController(regVC, animated: true)
                    }
                }else{
                    let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                    alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                    DispatchQueue.main.async {
                        self.present(alert, animated: true, completion: nil)
                    }
                }
                
            }catch let ex{
                let alert = UIAlertController(title: "请求出错", message: nil, preferredStyle: .alert)
                alert.addAction(UIAlertAction(title: "OK", style: .cancel, handler: nil))
                DispatchQueue.main.async {
                    self.present(alert, animated: true, completion: nil)
                }
                print(ex)
            }
            }.resume()
    }
    
    func dismissAll(){
        dismiss(animated: true, completion: nil)
    }
    
    func resendSmsTimer(){
        if !getSmsCodeBtn.isEnabled {
            if smsCountdown < 0{
                getSmsCodeBtn.setTitle("获取验证码", for: UIControlState())
                getSmsCodeBtn.isEnabled = true
                smsCountdown = 60
                return
            }
            getSmsCodeBtn.setTitle("\(smsCountdown)s", for: UIControlState())
            smsCountdown -= 1
        }
        
    }
    
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
    

    /*
    // MARK: - Navigation

    // In a storyboard-based application, you will often want to do a little preparation before navigation
    override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        // Get the new view controller using segue.destinationViewController.
        // Pass the selected object to the new view controller.
    }
    */

}
